package com.amigo.online.provider.user.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;

@WebFilter(filterName="MyFilter",urlPatterns="/getAll/*")
@Slf4j
@Component
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest requestWrapper = null;
        //解决body不能多次读取的问题
        if(request instanceof HttpServletRequest) {
            requestWrapper= new RequestWrapper((HttpServletRequest) request);
        }
        if(requestWrapper == null){
            requestWrapper = (HttpServletRequest) request;
        }
        Enumeration<String> headerNames = requestWrapper.getHeaderNames();
        StringBuilder stringBuilder = new StringBuilder();


        String requestURI = requestWrapper.getRequestURI();
        log.info("过滤到的请求--->"+requestURI);
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String values = requestWrapper.getHeader(name);
            stringBuilder.append("-->headerName：" + name + "，value：" +  values + "；");
        }
        log.info("HEADER：" + stringBuilder.toString());
        if(requestWrapper.getMethod().equals("POST")||requestWrapper.getMethod().equals("PUT")){
            String body = getParm(requestWrapper);
            log.info("body：" + body);
        }

        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }

    }

    /**
     * 获取POST请求中Body参数
     * @param request
     * @return 字符串
     */
    public String getParm(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            //  Auto-generated catch block
            e.printStackTrace();
        }
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            //  Auto-generated catch block
            e.printStackTrace();
        }
        return sb.toString();
    }
    @Override
    public void destroy() {

    }
}
